package com.example.scenictourback.service.impl;

import com.example.scenictourback.dto.PaymentDTO;
import com.example.scenictourback.entity.Order;
import com.example.scenictourback.entity.Payment;
import com.example.scenictourback.repository.OrderRepository;
import com.example.scenictourback.repository.PaymentRepository;
import com.example.scenictourback.service.PaymentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityNotFoundException;
import java.util.Date;
import java.util.List;
import java.util.Optional;

@Service
public class PaymentServiceImpl implements PaymentService {
    
    @Autowired
    private PaymentRepository paymentRepository;
    
    @Autowired
    private OrderRepository orderRepository;

    @Override
    @Transactional
    public PaymentDTO createPayment(PaymentDTO paymentDTO) {
        // 检查订单是否存在
        Order order = orderRepository.findById(paymentDTO.getOrderId())
                .orElseThrow(() -> new EntityNotFoundException("订单不存在"));
        
        // 创建支付实体
        Payment payment = new Payment();
        payment.setOrder(order);
        payment.setAmount(order.getTotalAmount());
        payment.setMethod(paymentDTO.getMethod());
        
        // 保存支付记录
        Payment savedPayment = paymentRepository.save(payment);
        
        return PaymentDTO.fromEntity(savedPayment);
    }

    @Override
    @Transactional
    public PaymentDTO processPayment(Integer orderId, Integer paymentMethod) {
        // 检查订单是否存在
        Order order = orderRepository.findById(orderId)
                .orElseThrow(() -> new EntityNotFoundException("订单不存在"));
        
        // 检查订单状态，只有未支付的订单可以处理支付
        if (order.getStatus() != 1) {
            throw new IllegalStateException("订单状态不正确，无法支付");
        }
        
        // 检查是否已有支付记录
        List<Payment> existingPayments = paymentRepository.findByOrderId(orderId);
        Payment payment;
        
        if (!existingPayments.isEmpty()) {
            payment = existingPayments.get(0);
        } else {
            // 创建新的支付记录
            payment = new Payment();
            payment.setOrder(order);
            payment.setAmount(order.getTotalAmount());
            payment.setMethod(paymentMethod);
        }
        
        // 设置支付时间
        payment.setPayTime(new Date());
        
        // 保存支付记录
        Payment savedPayment = paymentRepository.save(payment);
        
        return PaymentDTO.fromEntity(savedPayment);
    }

    @Override
    public PaymentDTO getPaymentById(Integer id) {
        Payment payment = paymentRepository.findById(id)
                .orElseThrow(() -> new EntityNotFoundException("支付记录不存在"));
        
        return PaymentDTO.fromEntity(payment);
    }

    @Override
    public PaymentDTO getPaymentByOrderId(Integer orderId) {
        List<Payment> payments = paymentRepository.findByOrderId(orderId);
        if (payments.isEmpty()) {
            throw new EntityNotFoundException("支付记录不存在");
        }
        
        return PaymentDTO.fromEntity(payments.get(0));
    }
} 